package logic

import (
	"context"
	"fmt"
	"product_zc/models/cache"
	"product_zc/models/mysql"
	"product_zc/pkg"
	"product_zc/productRpc/internal/svc"
	"product_zc/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *productRpc.LoginRequest) (*productRpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{}
	mysql.DB.Where("account=?", in.Tel).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在")
	}

	if in.Password == "" {
		if in.SmsCode == "" {
			return nil, fmt.Errorf("短信验证码不能为空！")
		}

		sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
		if sms != in.SmsCode {
			return nil, fmt.Errorf("短信验证码错误！")
		}
	} else {
		if user.Password != pkg.Md5(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	}

	cache.Rdb.Del(l.ctx, "sendSms"+in.Tel)

	return &productRpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
